package com.woyou.fragment.goods;

import java.util.ArrayList;
import java.util.List;

import com.jing.biandang.R;
import com.woyou.activity.HomeActivity;
import com.woyou.adapter.GoodsManagerAdapter;
import com.woyou.adapter.GoodsManagerRightAdapter;
import com.woyou.bean.FmInfo;
import com.woyou.bean.GoodsInfo;
import com.woyou.bean.GoodsTypeInfo;
import com.woyou.bean.rpc.QueryGoodsListReq;
import com.woyou.bean.rpc.QueryTypeListReq;
import com.woyou.bean.rpc.Result;
import com.woyou.component.SuperUI;
import com.woyou.fragment.SuperFragment;
import com.woyou.model.rpc.ShopModel;
import com.woyou.utils.LoginUtils;
import com.woyou.utils.ThreadPoolManager;
import com.woyou.utils.TypeJudgeTools;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;

public class GoodsManagerFragment extends SuperFragment implements OnClickListener {
	private HomeActivity homeActivity;
	private View layout_gm;
	// 左边全部列表
	private ListView layout_gm_all_lv;
	private GoodsManagerAdapter gmAdapter;
	List<GoodsTypeInfo> goodsTypeList = new ArrayList<GoodsTypeInfo>();
	private int currentCheck = 0;
	private EditText layout_gm_et;
	private String keyWord;
	private ImageView layout_gm_clear;
	// 右边详情
	private GridView layout_gm_some_gv;
	private List<GoodsInfo> goodsList = new ArrayList<GoodsInfo>();
	private GoodsManagerRightAdapter gmRightAdapter;
//	private ResultOld<SettingsGoods> allRightList;

	private Handler handler;
	private Message msg;
	
	Result<List<GoodsTypeInfo>> result = null;
	Result<List<GoodsInfo>> queryGoodsListResult = null;

	@Override
	public void onHiddenChanged(boolean hidden) {
		if (!hidden) {
			//延迟500毫秒执行，确保切换流畅
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					loadAllData();
				}
			}, 500);
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		layout_gm = inflater.inflate(R.layout.layout_goodsmanager, container, false);
		homeActivity=(HomeActivity)getActivity();
		return layout_gm;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initView();
	}

	/**
	 * 初始化View
	 */
	public void initView() {
		// 左边全部商品
		layout_gm_all_lv = (ListView) layout_gm.findViewById(R.id.layout_gm_all_lv);
		gmAdapter = new GoodsManagerAdapter(homeActivity, goodsTypeList);
		layout_gm_all_lv.setAdapter(gmAdapter);
		layout_gm_all_lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
				gmAdapter.setSelectItem(position);
				gmAdapter.notifyDataSetInvalidated();
				currentCheck = position;
				// 刷新右边数据
				loadCategoryData(goodsTypeList.get(position).gettId());
			}
		});

		// 右边详情
		layout_gm_et = (EditText) layout_gm.findViewById(R.id.layout_gm_et);
		// 清除搜索框的内容
		layout_gm_clear = (ImageView) layout_gm.findViewById(R.id.layout_gm_clear);
		layout_gm_clear.setOnClickListener(this);
		layout_gm_et.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				keyWord = layout_gm_et.getText().toString();
				if (!TypeJudgeTools.isNull(keyWord)) {
					layout_gm_clear.setVisibility(View.VISIBLE);
				} else {
					SuperUI.openToast(homeActivity, "请输入关键字");
					layout_gm_clear.setVisibility(View.GONE);
				}

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		layout_gm_some_gv = (GridView) layout_gm.findViewById(R.id.layout_gm_some_gv);
		gmRightAdapter = new GoodsManagerRightAdapter(homeActivity, goodsList);
		layout_gm_some_gv.setAdapter(gmRightAdapter);
		layout_gm_some_gv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				String categoryName = goodsTypeList.get(currentCheck).gettName();
				// 放置categoryPosition
				aCache.put("categoryPosition", position + "");
				// 放置categoryName
				aCache.put("categoryName", categoryName);
				GoodsInfo goodsInfo = goodsList.get(position);
				// 放置settingsGoods
				aCache.put("settingsGoods", goodsInfo);
				jump2GMDetails();
			}
		});

		dealwithMessage();
		loadAllData();
	}

	/**
	 * 跳转到商品详情
	 * 
	 * @param settingsGoods
	 */
	public void jump2GMDetails() {
		homeActivity.openSubFM(this, new FmInfo(GoodsDetailsFragment.class, "编辑商品", false));
	}

	// 生成一个处理消息的handler
	public void dealwithMessage() {

		/**
		 * 处理数据 msg.arg1 1:表示暂缺商品 2:表示所有商品 3:表示右边分类的列表 msg.arg2
		 * 0表示不clear原始数据,1表示先clear原始数据并刷新列表 msg.obj:携带真实的数据类型
		 */
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.arg1) {
				case 1:
					if (msg.obj != null) {
						List<GoodsTypeInfo> gTypeList = (List<GoodsTypeInfo>) msg.obj;
						// 左边类别列表更新
						goodsTypeList.clear();
						goodsTypeList.addAll(gTypeList);
						gmAdapter.notifyDataSetChanged();
						// 右边类别列表数据更新
						loadCategoryData(goodsTypeList.get(currentCheck).gettId());
					}
					break;
				case 2:
					if (msg.obj != null) {
						List<GoodsInfo> gList = (List<GoodsInfo>) msg.obj;
						goodsList.clear();
						goodsList.addAll(gList);
						gmRightAdapter.notifyDataSetChanged();
					}
					break;
				}
			}

		};
	}

	/**
	 * 载入本店所有数据并适配全部商品数据
	 */
	public void loadAllData() {
		ThreadPoolManager.getInstance().executeTask(new Runnable() {
			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					QueryTypeListReq queryTypeListReq = new QueryTypeListReq();
					queryTypeListReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
					queryTypeListReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
					result = ShopModel.getInstance(homeActivity).queryTypeList(queryTypeListReq);
					if (result != null && result.code==1) {
						List<GoodsTypeInfo> goodsTypeInfo = result.getData();
						// 重组数据 移除掉allCategoryList中的全部商品
						for (int i = 0; i < goodsTypeInfo.size(); i++) {
							if (goodsTypeInfo.get(i).getgNum()==0) {
								goodsTypeInfo.remove(goodsTypeInfo.get(i));
							}
						}
						msg = new Message();
						msg.arg1 = 1;
						msg.obj = goodsTypeInfo;
						handler.sendMessage(msg);
					} else if( result != null && result.code==-3 ) {
						homeActivity.homeController.exitLogin();
					} else {
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								SuperUI.openToast(homeActivity, result.msg);
							}
						});
					}
				} catch (Exception e) {
					e.printStackTrace();
					homeActivity.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							SuperUI.openToast(homeActivity, "请检查网络连接！");
						}
					});
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}

	/**
	 * 传入分类id 获取分类列表详情
	 * 
	 * @param cgy
	 */
	public void loadCategoryData(final String cgy) {
		ThreadPoolManager.getInstance().executeTask(new Runnable() {

			@Override
			public void run() {
				try {
					homeActivity.showLoadingHint();
					QueryGoodsListReq queryGoodsListReq = new QueryGoodsListReq();
					queryGoodsListReq.setsId(LoginUtils.getUserInfo(homeActivity).getsId());
					queryGoodsListReq.settId(cgy);
					queryGoodsListReq.setPwd(LoginUtils.getUserInfo(homeActivity).getPwd());
					queryGoodsListResult = ShopModel.getInstance(homeActivity).queryGoodsList(queryGoodsListReq);
					if (result != null && result.code==1) {
						msg = new Message();
						msg.arg1 = 2;
						msg.obj = queryGoodsListResult.getData();
						handler.sendMessage(msg);
					} else if( result != null && result.code==-3 ) {
						homeActivity.homeController.exitLogin();
					} else {
						homeActivity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								SuperUI.openToast(homeActivity, queryGoodsListResult.msg);
							}
						});
					}
				} catch (Exception e) {
					e.printStackTrace();
					homeActivity.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							// TODO Auto-generated method stub
							SuperUI.openToast(homeActivity, "请检查网络连接！");
						}
					});
				} finally {
					homeActivity.hideLoadingHint();
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_gm_clear:
			layout_gm_et.setText("");
			break;
		}

	}
}
